package com.itpan.Controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itpan.Entity.Customer;
import com.itpan.Entity.Dto.ProductDto;
import com.itpan.Entity.Product;
import com.itpan.Entity.PurchaseOrderDetail;
import com.itpan.Service.CustomerService;
import com.itpan.Service.ProductService;
import com.itpan.Service.PurchaseOrderDetailService;
import com.itpan.Utils.EntityValidate;
import com.itpan.Utils.ImageUtils;
import com.itpan.Utils.ProductExcelListener;
import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Api(value = "产品接口")
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private EntityValidate entityValidate;
//    @Autowired
//    private PurchaseOrderService purchaseOrderService;
//
    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private ImageUtils imageUtils;

    /*
    查询所有
     */
    @Cacheable(value = "product",key = "'all'")
    @ApiOperation(value = "查询所有商品信息")
    @GetMapping("/all")
    public R<List<Product>> getAll(){
        List<Product> all = productService.getAll();
        return R.success(all);
    }

    /*
    查询所有商品带分页
     */
    @Cacheable(value = "product",key = "#p0"+'-'+"#p1")
    @ApiOperation("查询所有商品带分页")
    @PostMapping("/getallpage")
    public R<List<Product>> getAllPage(Integer page,Integer pageSize){
        List<Product> list = productService.getAllPage(page, pageSize);
        return R.success(list);
    }

    /*
    查询所有商品到表格
     */
    @CacheEvict(value = "product",allEntries = true)
    @ApiOperation(value = "批量导入商品")
    @PostMapping("/import")
    public R<String> importProductList(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }
        EasyExcel.read(file.getInputStream(), Product.class, new ProductExcelListener(productService, customerService, entityValidate))
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doRead();
        return R.success("文件上传成功");
    }

    /*
    批量导出，excle下载
     */
    @ApiOperation(value = "表格下载")
    @RequestMapping(value = "/getalltable", method = RequestMethod.GET)
    public void exportMemberList(HttpServletResponse response) throws IOException {
        setExcelRespProp(response, "商品列表");
        List<Product> list = productService.getAll();
        EasyExcel.write(response.getOutputStream(), Product.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("商品列表")
                .doWrite(list);
        response.getOutputStream().flush();  // Ensure all data is written to the response
    }


    @ApiOperation(value = "模糊查询不带表格")
    @PostMapping("/getbymutil")
  public R<List<Product>> getbymutil(@RequestBody Product product){
        List<Product> list = productService.getbymutil(product);
        return R.success(list);
    }


    @ApiOperation(value = "模糊查询带表格")
    @PostMapping("/getbymutiltable")
    public void getbymutiltable(@RequestBody Product product,HttpServletResponse response) throws IOException {
        List<Product> list = productService.getbymutil(product);
        setExcelRespProp(response, "商品列表");
        EasyExcel.write(response.getOutputStream(), Product.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("商品列表")
                .doWrite(list);
        response.getOutputStream().flush();  // Ensure all data is written to the response
    }


    /*
    根据名字查询信息//模糊查询
     */
    @Cacheable(value = "product",key = "#p0")
    @ApiOperation("根据商品名称查询商品")
    @GetMapping("/getbyname")
    public R<List<Product>> getByName(String Name){
        List<Product> list = productService.getByName(Name);
        return R.success(list);
    }



    /*
    查询一个商品在订单明细里的全部记录
     */
    @GetMapping("getrecord")
    @ApiOperation("根据商品id查找采购记录")
    public R<List<PurchaseOrderDetail>>  getallrecordById(@PathParam(value = "Id") String Id){
        List<PurchaseOrderDetail> list = purchaseOrderDetailService.getProductByPid(Id);
        return R.success(list);
    }


    /*
    插入一个商品
     */
    @CacheEvict(value = "product",allEntries = true)
    @ApiOperation(value = "添加一个商品")
    @PostMapping("/addone")
    public R<String> addone(@ModelAttribute ProductDto productDto, @RequestParam("file")MultipartFile file){

        //先判断供应商存不存在
        Customer cus = customerService.getById(productDto.getSupplierID());

        if(cus==null){
            return R.error("供应商不存在");
        }


        //实行存入逻辑
        String img = imageUtils.saveAndgetNewName(file);
        Product product=new Product();
        //复制
        BeanUtils.copyProperties(productDto,product);
        product.setImage(img);
        if (!entityValidate.isValidateOfProduct(product)){
            return R.error("信息填写错误");
        }
        productService.saveOne(product);
        return R.success("添加成功");
    }


    /*
    更新一个商品
     */
    @CacheEvict(value = "product",allEntries = true)
    @PostMapping("/update")
    @ApiOperation(value = "更新商品数据")
    public R<String> update(@ModelAttribute ProductDto productDto,@RequestParam("file")MultipartFile file){

        //先判断供应商存不存在
        Customer cs = customerService.getById(productDto.getSupplierID());
        if(cs==null) return R.error("供应商不存在");

        String img = imageUtils.saveAndgetNewName(file);
        Product product=new Product();
        //Dto转bean
        BeanUtils.copyProperties(productDto,product);
        //复制后再复制img
        product.setImage(img);

        if (!entityValidate.isValidateOfProduct(product)){
            return R.error("信息填写错误");
        }
        productService.update(product);
        return R.success("更新成功");
    }




    @ApiOperation(value = "根据id删除商品")
    @DeleteMapping("/delete")
    @CacheEvict(value = "product",allEntries = true)
    public R<String> deleteByid(String id){

        //先去判断有没有商品在采购明细里面，有则不能删除，没有则可以删除

        //拿到商品
        Product product = productService.getById(id);


        //去看有没有相应的采购明细
//        PurchaseOrder po = purchaseOrderService.getById(product.getProductID());
        List<PurchaseOrderDetail> po = purchaseOrderDetailService.getProductByPid(product.getProductID());


        if(po.size()>0){
            return R.error("删除失败，采购表中还有相关采购记录");
        }

        //如果没有相关记录就可以删除
        productService.delete(id);
        return R.success("删除成功");
    }


    //excel响应头
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // Ensure the file is not cached
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }
}
